package com.tengju.user.domain.shared;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;

@Slf4j
public class AESUtil {

    private static final String KEY_ALGORITHM = "AES";
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";


    private AESUtil() {
    }

    /**
     * 加密数据
     *
     * @param content 内容
     * @param key     秘钥
     */
    public static String encryptDES(String content, String key) {
        try {
            if (content == null) {
                return null;
            }
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(getKey(key), "DES"));
            byte[] encryptedData = cipher.doFinal(content.getBytes("UTF-8"));
            return Base64.encodeBase64String(encryptedData);
        } catch (Exception e) {
            log.error("加密失败", e);
            return null;
        }
    }

    /**
     * key  不足8位补位
     */
    public static byte[] getKey(String keyRule) {
        Key key = null;
        byte[] keyByte = keyRule.getBytes();
        // 创建一个空的八位数组,默认情况下为0
        byte[] byteTemp = new byte[8];
        // 将用户指定的规则转换成八位数组
        for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
            byteTemp[i] = keyByte[i];
        }
        key = new SecretKeySpec(byteTemp, "DES");
        return key.getEncoded();
    }

    /***
     * 解密数据
     * @param content 内容
     * @param key 秘钥
     */

    public static String decryptDES(String content, String key) {
        try {
            if (content == null) {
                return null;
            }
            byte[] sourceBytes = Base64.decodeBase64(content);
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(getKey(key), "DES"));
            byte[] decoded = cipher.doFinal(sourceBytes);
            return new String(decoded, "UTF-8");
        } catch (Exception e) {
            log.error("解密失败", e);
            return null;
        }

    }

    /**
     * @param keyStr 进行了Base64编码的秘钥
     * @param data   需要进行加密的原文
     * @return String 数据密文，加密后的数据，进行了Base64的编码
     * @desc: AES对称-加密操作
     */
    public static String encrypt(String keyStr, String data) {
        try {
            // 转换密钥
            Key key = new SecretKeySpec(Base64Util.decode(keyStr), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            // 加密
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(data.getBytes());
            return Base64Util.encode(result);
        } catch (Exception e) {
            log.warn("encrypt error", e);
            return data;
        }
    }



    /**
     * @param keyStr 进行了Base64编码的秘钥
     * @param data   需要解密的数据<span style="color:red;">（数据必须是通过AES进行加密后，对加密数据Base64编码的数据）</span>
     * @return String 返回解密后的原文
     * @desc: AES对称-解密操作
     */
    public static String decrypt(String keyStr, String data) {
        try {
            // 转换密钥
            Key key = new SecretKeySpec(Base64Util.decode(keyStr), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            // 解密
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(Base64Util.decode(data));
            return new String(result);
        } catch (Exception e) {
            log.warn("decrypt error", e);
            return data;
        }
    }

    /**
     * @return String 对生成的秘钥进行了Base64编码的字符串
     * @desc: 生成AES的秘钥，秘钥进行了Base64编码的字符串
     * @author: yong.li
     * @createTime: 2018年8月28日 上午10:24:32
     * @version: v0.0.1
     */
    public static String keyGenerate() throws Exception {
        // 生成密钥
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        keyGenerator.init(new SecureRandom());
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] keyBytes = secretKey.getEncoded();
        return Base64Util.encode(keyBytes);
    }

    public static void main(String[] args) throws Exception {
        System.out.println(decrypt(Constant.USERID_ENCRYPT_KEY,"woehRdBwAA_1XdxUhFAA1f2eTZxEeguA"));
    }


}
